#include "ImportProcessWindow.h"
#include <QMessageBox>
#include <QThread>
#include "AutoImportWindow.h"


ImportProcessWindow::ImportProcessWindow(QString zipPath, QWidget *parent) : QWidget(parent)
{
    connect(this, &ImportProcessWindow::finished, parent, &AutoImportWindow::close);

    progressBar = new QProgressBar(this);
    progressBar->setRange(0, 100);
    progressBar->setValue(0);

    label = new QLabel(this);
    label->setText("Processing...");

    mainLayout = new QVBoxLayout();
    mainLayout->addWidget(progressBar);
    mainLayout->addWidget(label);

    // start import thread
    workThread = new ImportThread(zipPath);
    connect(workThread, SIGNAL(handle(ImportHandleStatus,int,QString)), this, SLOT(handle(ImportHandleStatus,int,QString)), Qt::BlockingQueuedConnection);
    connect(workThread, &ImportThread::handle, this, &ImportProcessWindow::handle);
    workThread->start();


    setLayout(mainLayout);
    setFixedSize(600, 64);
    setWindowFlags(Qt::Window);
}

ImportProcessWindow::~ImportProcessWindow()
{
    delete mainLayout;
    delete progressBar;
    delete label;
    workThread->wait();
}

void ImportProcessWindow::handle(ImportHandleStatus status, int process, QString text)
{
    switch (status)
    {
        case Finished:
            QMessageBox::information(nullptr, tr("import_finished_title"), tr("import_finished_text"));
            cleanAndClose();
            emit finished();
            break;
        case UpdateLabel:
            label->setText(text);
            break;
        case UpdateProcess:
            progressBar->setValue(process);
            break;
        case UpdateLabelAndPrcess:
            label->setText(text);
            progressBar->setValue(process);
            break;
        case FileNotExists:
            QMessageBox::critical(nullptr, tr("zip_not_exists_title"), tr("zip_not_exists_text"));
            cleanAndClose();
            break;
        case FileCannotOpen:
            QMessageBox::critical(nullptr, tr("zip_cannot_open_title"), tr("zip_cannot_open_text"));
            cleanAndClose();
            break;
        case FileVerificationFailed:
            QMessageBox::critical(nullptr, tr("zip_verifcation_failed_title"), tr("zip_verifcation_failed_text"));
            cleanAndClose();
            break;
        default:
            break;
    }
}


void ImportProcessWindow::cleanAndClose()
{
    close();
}

void ImportProcessWindow::closeEvent(QCloseEvent *event)
{
    if (workThread) workThread->Cancel();
    QWidget::closeEvent(event);
}
